package com.loto.insurance.mis.web.controller;

import java.util.Calendar;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.loto.insurance.framework.InsFactory;
import com.loto.insurance.framework.Air.InsAir;
import com.loto.insurance.framework.Air.InsReturnMsg;
import com.loto.insurance.framework.Air.OrderItemInfo;
import com.loto.insurance.mis.web.authority.INSAuthority;
import com.loto.insurance.mis.web.entity.config.MenuConfig;
import com.loto.insurance.mis.web.enumeration.MenuEnum;
import com.loto.insurance.mis.web.utils.Config;

@Controller
public class HomeController {
  @INSAuthority
  @RequestMapping(value = "/")
  public String home() {
	return "home";
  }

  @RequestMapping(value = "/login")
  public String login() {
	return "login";
  }

  @RequestMapping(value = "/ctrl/header")
  public String header() {
	return "ctrl/header";
  }

  @RequestMapping(value = "/ctrl/simpleheader")
  public String simpleheader() {
	return "ctrl/header_without_easyui";
  }

  @RequestMapping(value = "/ctrl/top")
  public String top(
	  @RequestParam(value = "subId", required = false, defaultValue = "0") int subId,
	  HttpServletRequest request, Model model) {
	MenuConfig menuConfig = Config.getMenuConfigFile(request);
	model.addAttribute("menuList", menuConfig);
	if (subId != 0) {
	  for (MenuEnum m : MenuEnum.values())
		if (m.getIndex() == subId) {
		  model.addAttribute("subId", subId);
		  model.addAttribute("mainId", m.getParentId());
		  break;
		}
	}
	// String aa = request.getRequestURI();
	return "ctrl/top";
  }

  private void testBDFZ() {
	Calendar now = Calendar.getInstance();
	now.add(Calendar.DAY_OF_MONTH, 2);
	InsAir ins = InsFactory.GenerateInsAirProcessor("BDFZ", "ETPA_01");
	/*
	 * OrderItemInfo info = new OrderItemInfo(); info.setFlightNo("");
	 * info.setFromPeriod(now.getTime()); Calendar holderBirth =
	 * Calendar.getInstance(); holderBirth.set(1978, 7, 2);
	 * info.setHolderBirth(holderBirth.getTime());
	 * info.setHolderCredentialNo("420104197807021218");
	 * info.setHolderCredentialType("身份证"); info.setHolderGender("男");
	 * info.setHolderName("刘凡"); info.setTransOrderNo("420104197807021218");
	 * info.setInsuredBirth(holderBirth.getTime());
	 * info.setInsuredCredentialNo("420104197807021218");
	 * info.setInsuredCredentialType("身份证"); info.setInsuredEmail("");
	 * info.setInsuredGender("男"); info.setInsuredName("刘凡");
	 * info.setInsuredTel("13312345678"); InsReturnMsg msg =
	 * ins.PolicyApproval(info);
	 */

	OrderItemInfo cItemInfo = new OrderItemInfo();
	cItemInfo.setInsuranceNo("7120021472");
	InsReturnMsg m = ins.PolicyCancel(cItemInfo);
  }

  private void testCPIC() {
	Calendar now = Calendar.getInstance();
	now.add(Calendar.DAY_OF_MONTH, 2);
	// 投保
	InsAir ins = InsFactory.GenerateInsAirProcessor("CPIC", "SJX102_12");
	/*
	 * OrderItemInfo info = new OrderItemInfo(); info.setFlightNo("");
	 * info.setFromPeriod(now.getTime()); Calendar holderBirth =
	 * Calendar.getInstance(); holderBirth.set(1978, 7, 2);
	 * info.setHolderBirth(holderBirth.getTime());
	 * info.setHolderCredentialNo("420104197807021218");
	 * info.setHolderCredentialType("身份证"); info.setHolderGender("男");
	 * info.setHolderName("刘凡"); info.setTransOrderNo("420104197807021218");
	 * info.setInsuredBirth(holderBirth.getTime());
	 * info.setInsuredCredentialNo("420104197807021218");
	 * info.setInsuredCredentialType("身份证"); info.setInsuredEmail("");
	 * info.setInsuredGender("男"); info.setInsuredName("刘凡");
	 * info.setInsuredTel("13312345678"); InsReturnMsg msg =
	 * ins.PolicyApproval(info);
	 */

	// 020471443861613 033706

	// 查询
	/*
	 * OrderItemInfo queryItemInfo = new OrderItemInfo();
	 * queryItemInfo.setTransOrderNo("420104197807021218");
	 * queryItemInfo.setInsuredCredentialType("身份证");
	 * queryItemInfo.setInsuredCredentialNo("420104197807021218");
	 * queryItemInfo.setInsuranceNo("020471443861613"); InsReturnMsg msg =
	 * ins.PolicyQuery(queryItemInfo);
	 */

	// 退保020471443940642/020471443940836
	OrderItemInfo cItemInfo = new OrderItemInfo();
	cItemInfo.setInsuranceNo("020471443940642");
	InsReturnMsg m = ins.PolicyCancel(cItemInfo);
  }

  private void test() {
	Properties systemProps = System.getProperties();
	systemProps.put("javax.net.ssl.trustStore", "jssecacerts");
	System.setProperties(systemProps);

	try {
	  // Open a secure connection.
	  URL url = new URL(
		  "https://eairiis-prddmz.paic.com.cn/invoke/wm.tn/receive");
	  String requestParams = "uid=1233333";
	  HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

	  // Set up the connection properties
	  con.setRequestProperty("Connection", "close");
	  con.setDoInput(true);
	  con.setDoOutput(true);
	  con.setUseCaches(false);
	  con.setConnectTimeout(30000);
	  con.setReadTimeout(30000);
	  con.setRequestMethod("POST");
	  con.setRequestProperty("Content-Type",
		  "application/x-www-form-urlencoded");
	  con.setRequestProperty("Content-Length",
		  Integer.toString(requestParams.length()));

	  // Set up the user authentication portion of the handshake with the
	  // private
	  // key provided by NAIMES Tech Support.
	  // Based on an example posted by Torsten Curdt on his blog:
	  // http://vafer.org/blog/20061010073725 (as of Nov, 2009)
	  File pKeyFile = new File("e:\\EXV.pfx");
	  String pKeyPassword = "guodu2009";
	  KeyManagerFactory keyManagerFactory = KeyManagerFactory
		  .getInstance("SunX509");
	  KeyStore keyStore = KeyStore.getInstance("PKCS12");
	  InputStream keyInput = new FileInputStream(pKeyFile);
	  keyStore.load(keyInput, pKeyPassword.toCharArray());
	  keyInput.close();
	  keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());
	  SSLContext context = SSLContext.getInstance("TLS");
	  context
		  .init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
	  SSLSocketFactory sockFact = context.getSocketFactory();
	  con.setSSLSocketFactory(sockFact);

	  // Send the request
	  OutputStream outputStream = con.getOutputStream();
	  outputStream.write(requestParams.getBytes("UTF-8"));
	  outputStream.close();

	  // Check for errors
	  int responseCode = con.getResponseCode();
	  InputStream inputStream;
	  if (responseCode == HttpURLConnection.HTTP_OK) {
		inputStream = con.getInputStream();
	  } else {
		inputStream = con.getErrorStream();
	  }

	  // Process the response
	  BufferedReader reader;
	  String line = null;
	  reader = new BufferedReader(new InputStreamReader(inputStream));
	  while ((line = reader.readLine()) != null) {
		System.out.println(line);
	  }

	  inputStream.close();
	} catch (Exception e) {
	  e.printStackTrace();
	}
  }

  private void testPICC() {
	Calendar now = Calendar.getInstance();
	now.add(Calendar.DAY_OF_MONTH, 2);
	InsAir ins = InsFactory.GenerateInsAirProcessor("PICC", "SHHYX");
	OrderItemInfo info = new OrderItemInfo();
	info.setFlightNo("");
	info.setFromPeriod(now.getTime());
	Calendar holderBirth = Calendar.getInstance();
	holderBirth.set(1978, 7, 2);
	info.setHolderBirth(holderBirth.getTime());
	info.setHolderCredentialNo("420104197807021218");
	info.setHolderCredentialType("身份证");
	info.setHolderGender("男");
	info.setHolderName("刘凡");
	info.setTransOrderNo("420104197807021218");
	info.setInsuredBirth(holderBirth.getTime());
	info.setInsuredCredentialNo("420104197807021218");
	info.setInsuredCredentialType("身份证");
	info.setInsuredEmail("");
	info.setInsuredGender("男");
	info.setInsuredName("刘凡");
	info.setInsuredTel("13312345678");
	InsReturnMsg msg = ins.PolicyApproval(info);
  }

  private void testTK() {
	Calendar now = Calendar.getInstance();
	now.add(Calendar.DAY_OF_MONTH, 2);
	InsAir ins = InsFactory.GenerateInsAirProcessor("TKSH", "10629009");
	OrderItemInfo info = new OrderItemInfo();
	info.setFlightNo("");
	info.setFromPeriod(now.getTime());
	Calendar holderBirth = Calendar.getInstance();
	holderBirth.set(1978, 7, 2);
	info.setHolderBirth(holderBirth.getTime());
	info.setHolderCredentialNo("420104197807021218");
	info.setHolderCredentialType("身份证");
	info.setHolderGender("男");
	info.setHolderName("刘凡");
	info.setTransOrderNo("420104197807021218");
	info.setInsuredBirth(holderBirth.getTime());
	info.setInsuredCredentialNo("420104197807021218");
	info.setInsuredCredentialType("身份证");
	info.setInsuredEmail("");
	info.setInsuredGender("男");
	info.setInsuredName("刘凡");
	info.setInsuredTel("13312345678");
	InsReturnMsg msg = ins.PolicyApproval(info);
  }

  private void testPA() {
	Calendar now = Calendar.getInstance();
	now.add(Calendar.DAY_OF_MONTH, 2);
	InsAir ins = InsFactory.GenerateInsAirProcessor("PASH", "P0122I4");
	OrderItemInfo info = new OrderItemInfo();
	info.setFlightNo("");
	info.setFromPeriod(now.getTime());
	Calendar holderBirth = Calendar.getInstance();
	holderBirth.set(1978, 7, 2);
	info.setHolderBirth(holderBirth.getTime());
	info.setHolderCredentialNo("420104197807021218");
	info.setHolderCredentialType("身份证");
	info.setHolderGender("男");
	info.setHolderName("刘凡");
	info.setTransOrderNo("420104197807021218");
	info.setInsuredBirth(holderBirth.getTime());
	info.setInsuredCredentialNo("420104197807021218");
	info.setInsuredCredentialType("身份证");
	info.setInsuredEmail("");
	info.setInsuredGender("男");
	info.setInsuredName("刘凡");
	info.setInsuredTel("13312345678");
	InsReturnMsg msg = ins.PolicyApproval(info);

	/*
	 * String host = "eairiis-prddmz.paic.com.cn"; int port = 443;
	 * 
	 * String fullFileName = "WEB-INF\\resources\\config\\EXV.pfx";//
	 * paConfigAir.getCertificatePath(); String path =
	 * this.getClass().getResource("").getPath() .replaceAll("%20", " "); String
	 * fileName = path.substring(0, path.indexOf("WEB-INF")) + fullFileName;
	 * 
	 * File file = new File("e:\\EXV.pfx");
	 * 
	 * System.out.println("Loading KeyStore " + file + "..."); InputStream in =
	 * new FileInputStream(file); KeyStore ks = KeyStore.getInstance("PKCS12");
	 * ks.load(in, "guodu2009".toCharArray()); in.close();
	 * 
	 * SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory
	 * tmf = TrustManagerFactory
	 * .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks);
	 * X509TrustManager defaultTrustManager = (X509TrustManager) tmf
	 * .getTrustManagers()[0]; SavingTrustManager tm = new
	 * SavingTrustManager(defaultTrustManager); context.init(null, new
	 * TrustManager[] { tm }, null); SSLSocketFactory factory =
	 * context.getSocketFactory();
	 * 
	 * System.out.println("Opening connection to " + host + ":" + port + "...");
	 * SSLSocket socket = (SSLSocket) factory.createSocket(host , port);
	 * socket.setSoTimeout(10000); try {
	 * System.out.println("Starting SSL handshake..."); socket.startHandshake();
	 * socket.close(); System.out.println();
	 * System.out.println("No errors, certificate is already trusted"); } catch
	 * (SSLException e) { System.out.println(); e.printStackTrace(System.out); }
	 * 
	 * X509Certificate[] chain = tm.chain; if (chain == null) {
	 * System.out.println("Could not obtain server certificate chain"); return
	 * ""; }
	 * 
	 * BufferedReader reader = new BufferedReader(new
	 * InputStreamReader(System.in));
	 * 
	 * System.out.println(); System.out.println("Server sent " + chain.length +
	 * " certificate(s):"); System.out.println(); MessageDigest sha1 =
	 * MessageDigest.getInstance("SHA1"); MessageDigest md5 =
	 * MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++)
	 * { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) +
	 * " Subject " + cert.getSubjectDN()); System.out.println("   Issuer  " +
	 * cert.getIssuerDN()); sha1.update(cert.getEncoded());
	 * System.out.println("   sha1    " + toHexString(sha1.digest()));
	 * md5.update(cert.getEncoded()); System.out.println("   md5     " +
	 * toHexString(md5.digest())); System.out.println(); }
	 * 
	 * System.out
	 * .println("Enter certificate to add to trusted keystore or 'q' to quit: [1]"
	 * ); String line = reader.readLine().trim(); int k; try { k =
	 * (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch
	 * (NumberFormatException e) { System.out.println("KeyStore not changed");
	 * return ""; }
	 * 
	 * X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1);
	 * OutputStream out = null; try { ks.setCertificateEntry(alias, cert);
	 * 
	 * out = new FileOutputStream("jssecacerts"); ks.store(out,
	 * "guodu2009".toCharArray()); out.close(); } catch (KeyStoreException |
	 * NoSuchAlgorithmException | CertificateException | IOException e) { //
	 * TODO Auto-generated catch block e.printStackTrace(); }
	 * 
	 * System.out.println(); System.out.println(cert); System.out.println();
	 * System.out
	 * .println("Added certificate to keystore 'jssecacerts' using alias '" +
	 * alias + "'");
	 */
  }

  private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

  private static String toHexString(byte[] bytes) {
	StringBuilder sb = new StringBuilder(bytes.length * 3);
	for (int b : bytes) {
	  b &= 0xff;
	  sb.append(HEXDIGITS[b >> 4]);
	  sb.append(HEXDIGITS[b & 15]);
	  sb.append(' ');
	}
	return sb.toString();
  }

  private static class SavingTrustManager implements X509TrustManager {

	private final X509TrustManager tm;
	private X509Certificate[] chain;

	SavingTrustManager(X509TrustManager tm) {
	  this.tm = tm;
	}

	public X509Certificate[] getAcceptedIssuers() {
	  throw new UnsupportedOperationException();
	}

	public void checkClientTrusted(X509Certificate[] chain, String authType)
	    throws CertificateException {
	  throw new UnsupportedOperationException();
	}

	public void checkServerTrusted(X509Certificate[] chain, String authType)
	    throws CertificateException {
	  this.chain = chain;
	  tm.checkServerTrusted(chain, authType);
	}
  }

}
